package org.chuan.hisports.service.Imp;

import org.chuan.hisports.dao.MemberDao;
import org.chuan.hisports.entity.AdMember;
import org.chuan.hisports.entity.Member;
import org.chuan.hisports.service.MemberService;
import org.chuan.hisports.util.CreatTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class MemberServiceImp implements MemberService {
    @Autowired
    MemberDao memberDao;
    //查询健身会员的所有信息
    @Override
    public Member select(String uid) {
        Member member = memberDao.select(uid);
        System.out.println(member.getUid());
        return member;
    }
    //查询会员到期时间
    @Override
    public String selectLastTime(String uid){


        String oldTime = memberDao.selectLastTime(uid);
        return oldTime;


    }
    //会员信息创建，向健身会员表插入数据

    @Override
    public void insert(Member member){
        memberDao.insert(member);

    }


    //会员充值更新
    @Override
    public void updateLevel(String uid, String month) {
        Member member = new Member();
        int num = Integer.parseInt(month);
        if (num >= 12){
            member.setLevel("包年");
        }else {
            member.setLevel("包月");
        }
        //将查询到的到期时间转换
        CreatTime ct = new CreatTime();
        //查看是否为空，为空则获得现在的时间
        String lasttime = selectLastTime(uid);
        if (lasttime == null || lasttime == ""){
            lasttime = ct.dataTime(ct.creatTime());
        }
        LocalDateTime oldTime = ct.dateTime(lasttime);
        //设置最后到期时间（查询到的最后时间与充值月数相加）
        member.setLasttime(timePlus(num,oldTime));
        member.setUid(uid);
        memberDao.updateLevel(member);

    }

    //月份相加,并返回字符串
    public String timePlus(int num, LocalDateTime lastTime){
        Period p = Period.ofMonths(num);
        LocalDateTime newTime = lastTime.plus(p);
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String strTime = dtf.format(newTime);
        return strTime;
    }


    //管理员查看相关信息
    @Override
    public List<AdMember> adminSelectMember(){
        List<AdMember> list = memberDao.selectAll();
        return list;
    }

}
